package response

import (
	"fmt"
	"gitee.com/libwiki/go-zero-lib/package/errorx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"runtime/debug"
)

type Body struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Success bool        `json:"success"`
	Data    interface{} `json:"data,omitempty"`
	Trail   string      `json:"trail"`
}

func Response(w http.ResponseWriter, resp any, err error) {
	var body Body
	if err != nil {
		body.Message = err.Error()
		if val, ok := err.(errorx.CodeError); ok {
			body.Code = val.Code()
		}
		body.Trail = fmt.Sprintf("%s", debug.Stack())
	} else {
		body.Message = "ok"
		body.Success = true
		body.Data = resp
	}
	httpx.OkJson(w, body)
}
